package com.example.studentims.controller;

import com.example.studentims.service.PhotoPathProvider;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.List;
import java.util.stream.Collectors;

@RestController
//@RequestMapping("/photos")
@RequestMapping("/api/photos")
public class PhotoController {

    @Autowired
    private PhotoPathProvider photoPathProvider;

    @GetMapping(value = { "", "/", "/**" })
    public List<String> listPhotos(HttpServletRequest request) throws IOException {
        // 获取完整请求路径，如 /photos/A/ 或 /photos/一/
        String uri = request.getRequestURI();

        // ✅ 正确移除 /api/photos 前缀，提取子目录路径
        String subPath = uri.replaceFirst("^/api/photos/?", "");

        // URL 解码，支持中文路径
        subPath = URLDecoder.decode(subPath, StandardCharsets.UTF_8);

        // 构造目标路径
        Path basePath = photoPathProvider.getPhotoPath();
        Path targetPath = subPath.isBlank() ? basePath : photoPathProvider.resolve(subPath);

        if (!Files.exists(targetPath) || !Files.isDirectory(targetPath)) {
            return List.of();
        }

        return Files.list(targetPath)
                .filter(Files::isRegularFile)
                .map(path -> {
                    Path relative = basePath.relativize(path);
                    return "/photos/" + relative.toString().replace("\\", "/");
                })
                .collect(Collectors.toList());
    }
}
